const express = require('express');
const jwt = require('jsonwebtoken');
const router = express.Router();
const { DeepseekUser, DeepSeekUserPhone } = require('../model/deepseekDb');

// 密钥，用于生成和验证 Token
const secretKey = 'token';

// 登陆
router.post('/login', async function (req, res, next) {
    const { username, password } = req.body;
    console.log(req.body);
    try {
        const user = await DeepseekUser.findOne({ username: username });
        if (!user) {
            return res.send({ code: 401, msg: '用户名不存在' });
        }
        if (user.password !== password) {
            return res.send({ code: 401, msg: '密码错误' });
        }
        const access_token = jwt.sign({ userId: user._id }, secretKey, { expiresIn: '1h' });
        const refresh_token = jwt.sign({ userId: user._id }, secretKey, { expiresIn: '1h' });

        res.send({ code: 200, msg: '登录成功', access_token, refresh_token });
    } catch (err) {
        console.error(err);
        res.status(500).send({ code: 500, msg: '服务器错误' });
    }
});

// 注册
router.post('/register', async function (req, res, next) {
    const { username, password } = req.body;
    console.log(req.body);
    try {
        const existingUser = await DeepseekUser.findOne({ username: username });
        if (existingUser) {
            return res.send({ code: 409, msg: '用户名已存在' });
        }
        const user = new DeepseekUser({
            username: username,
            password: password,
        });
        await user.save();

        res.send({ code: 200, msg: '注册成功' });
    } catch (err) {
        console.error(err);
        res.status(500).send({ code: 500, msg: '服务器错误' });
    }
});

// 验证手机号
router.post('/verify_phone', async function (req, res, next) {
    const { phone } = req.body;
    const formattedPhone = Number(phone);
    console.log(formattedPhone, '12345686');


    try {
        const user = await DeepSeekUserPhone.findOne({ phone: formattedPhone });
        console.log(user)
        if (!user) {
            return res.send({ code: 401, msg: '手机号不存在' });

        }
        res.send({ code: 200, msg: '手机号存在' });
    } catch (err) {
        console.error(err);
        res.status(500).send({ code: 500, msg: '服务器错误' });
    }
})


module.exports = router;